package com.bang.study.aggs;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.avg.InternalAvg;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @ClassName: ConstantScoreFilterAggs
 * @author: BANG
 * @Date: 2020/01/15 16:29
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 *
 * GET /tvs/sales/_search
 * {
 *   "size": 0,
 *   "query": {
 *     "constant_score": {
 *       "filter": {
 *         "range": {
 *           "price": {
 *             "gte": 1200
 *           }
 *         }
 *       }
 *     }
 *   },
 *   "aggs": {
 *     "avg_price": {
 *       "avg": {
 *         "field": "price"
 *       }
 *     }
 *   }
 * }
 */
public class ConstantScoreFilterAggs {

    public static void main(String[] args) throws UnknownHostException {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        SearchResponse searchResponse = client.prepareSearch("tvs").setTypes("sales")
                .setQuery(QueryBuilders.constantScoreQuery(QueryBuilders.boolQuery().filter(QueryBuilders.rangeQuery("price").gte(1200))))
                .addAggregation(AggregationBuilders.avg("avg_price").field("price"))
                .setSize(0)
                .get();

        InternalAvg avg_price = searchResponse.getAggregations().get("avg_price");
        System.err.println(avg_price.getValueAsString());

        client.close();

    }
}
